from flask import Blueprint, request, jsonify, current_app, url_for
import os
from werkzeug.utils import secure_filename
import uuid
from datetime import datetime
from flask import Blueprint, request, jsonify, current_app

# 创建上传API蓝图
upload_bp = Blueprint('upload', __name__)

# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

# 检查文件扩展名是否允许
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 生成唯一的文件名，避免冲突
def generate_unique_filename(filename):
    _, ext = os.path.splitext(filename)
    unique_id = uuid.uuid4().hex[:8]
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    return f"{timestamp}_{unique_id}{ext}"

# 图片上传API
@upload_bp.route('/upload/image', methods=['POST'])
def upload_image():
    # 检查请求中是否包含文件
    if 'file' not in request.files:
        return jsonify({'success': False, 'message': '没有文件被上传'}), 400
    
    file = request.files['file']
    
    # 检查文件名是否为空
    if file.filename == '':
        return jsonify({'success': False, 'message': '未选择文件'}), 400
    
    # 检查文件类型是否允许
    if file and allowed_file(file.filename):
        # 生成唯一的文件名
        filename = generate_unique_filename(file.filename)
        
        # 获取上传目录
        upload_folder = current_app.config['UPLOAD_FOLDER']
        
        # 确保上传目录存在
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)
        
        # 保存文件
        file_path = os.path.join(upload_folder, filename)
        file.save(file_path)
        
        # 构建图片URL
        image_url = f"/uploads/{filename}"
        
        # 返回成功响应和图片URL
        return jsonify({
            'success': True,
            'message': '图片上传成功',
            'image_url': image_url
        })
    
    # 文件类型不允许
    allowed_types = ', '.join(ALLOWED_EXTENSIONS)
    return jsonify({'success': False, 'message': f'不支持的文件类型。允许的类型：{allowed_types}'}), 400

# 在api/__init__.py中需要注册这个蓝图
def init_upload_api(api_bp):
    api_bp.register_blueprint(upload_bp, url_prefix='/admin')